package com.woniuxy.springcloud.zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.woniuxy.springcloud.common.entity.ResponseResult;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * description: LoginFilter <br>
 * date: 2022/1/24 4:39 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * Zuul过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 拦截类型：拦截器在什么时候执行
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 拦截器的执行顺序:越小优先级高
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否拦截：true:拦截，执行run
     * false:不拦截，不执行run
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获取请求上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String name = request.getParameter("name");
        if (!StringUtils.isEmpty(name)) {
            System.out.println("有name不拦截，直接放行");
            return false;
        }
        return true;
    }

    /**
     * 拦截器执行的代码
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("没有name,执行拦截方法,判断token");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            System.out.println("没有token，拦截，不能访问");
            currentContext.setSendZuulResponse(false);
            //currentContext.setResponseStatusCode(500);
            try {
                currentContext.setResponseBody(new ObjectMapper().writeValueAsString(
                        new ResponseResult<>(401, "authentication", "login first")));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("有token,放行");
        }
        return null;
    }
}
